package com.aote.component.block;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.aote.util.ComponentHelper;
import com.browsesoft.ExtendElement;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;

/**
 * 表格块组件 表格块组件本身不对页面进行处理。 只是对页面中得其他块组件进行管理，并对表格中得块组件得关系进行设置。
 */
public class HTMLTableBlockComponent extends HTMLBasicComponent {

	/**
	 * 表格头
	 */
	private HTMLBasicComponent headComponent = null;

	/**
	 * 表格体
	 */
	private HTMLBasicComponent leftComponent = null;

	/**
	 * 数据块组件
	 */
	private HTMLDatasBlockComponent datasComponent = null;

	public HTMLTableBlockComponent(HTMLBasicComponent parent) throws Exception {
		super(parent);
	}

	public void init(HttpServletRequest request, Element e) throws Exception {
		super.init(request, e);
		// 得到表格头，表格体，数据块组件
		this.headComponent = getHeadComponent();
		this.leftComponent = getLeftComponent();
		this.datasComponent = getDatasComponent();
		this.datasComponent.setBlockHeadComponent(this.headComponent);
		this.datasComponent.setBlockLeftComponent(this.leftComponent);
		this.datasComponent.setTableBlockComponent(this);
		
	}

	/**
	 * 得到表格头组件
	 */
	protected HTMLBasicComponent getHeadComponent() {
		try {
			Element elem = (Element) ExtendElement.findElements(this.getElement(),
					"blocktype", "head").get(0);
			String className = elem.getAttribute("component");
			return this.findComponent(this.getChildrenComponents(), className);
		} catch (RuntimeException e) {
			return null;
		}
	}

	/**
	 * 得到表格体组件
	 */
	protected HTMLBasicComponent getLeftComponent() {
		try {
			Element elem = (Element) ExtendElement.findElements(this.getElement(),
					"blocktype", "left").get(0);
			String className = elem.getAttribute("component");
			return this.findComponent(this.getChildrenComponents(), className);
		} catch (RuntimeException e) {
		    return null;
		}
	}

	/**
	 * 得到数据块组件
	 */
	protected HTMLDatasBlockComponent getDatasComponent() {
		Element elem = (Element) ExtendElement.findElements(this.getElement(),
				"blocktype", "datas").get(0);
		String className = elem.getAttribute("component");
		return (HTMLDatasBlockComponent) this.findComponent(this
				.getChildrenComponents(), className);
	}

	/**
	 * 根据类名称得到组件，从本组件的子组件和子组件的子组件中找
	 */
	private HTMLBasicComponent findComponent(Iterator childCompIter,
			String className) {
		HTMLBasicComponent result = ComponentHelper.findComponentInstance(
				childCompIter, className);
		if (result != null) {
			return result;
		}
		// 对于本组件每一个直接子
		Iterator iter = components.iterator();
		while (iter.hasNext()) {
			HTMLBasicComponent item = (HTMLBasicComponent) iter.next();
			result = ComponentHelper.findComponentInstance(item
					.getChildrenComponents(), className);
			if (result != null) {
				return result;
			}
		}
		return null;
	}

}
